package com.walker.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.net.ssl.SSLContext;

import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.ssl.TrustStrategy;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.client.RequestCallback;
import org.springframework.web.client.ResponseExtractor;
import org.springframework.web.client.RestTemplate;

import net.sf.json.JSONObject;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class RestTemplateUtil {

	public static RestTemplate getInstance(String charset) {
		RestTemplate restTemplate = new RestTemplate();
		List<HttpMessageConverter<?>> list = restTemplate.getMessageConverters();
		for (HttpMessageConverter<?> httpMessageConverter : list) {
			if (httpMessageConverter instanceof StringHttpMessageConverter) {
				((StringHttpMessageConverter) httpMessageConverter).setDefaultCharset(Charset.forName(charset));
			}
		}
		return restTemplate;
	}
	
	public static HttpComponentsClientHttpRequestFactory generateHttpRequestFactory()
			throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException {
		TrustStrategy acceptingTrustStrategy = (x509Certificates, authType) -> true;
		SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
		SSLConnectionSocketFactory connectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
				new NoopHostnameVerifier());

		HttpClientBuilder httpClientBuilder = HttpClients.custom();
		httpClientBuilder.setSSLSocketFactory(connectionSocketFactory);
		CloseableHttpClient httpClient = httpClientBuilder.build();
		HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
		factory.setHttpClient(httpClient);
		return factory;
	}

	public static String sendForPost(String url, Object params) {
	
		RestTemplate restT = RestTemplateUtil.getInstance("utf-8");
		return restT.postForObject(url, JSONObject.fromObject(params).toString(), String.class);
	}
	
	public static String sendForPost(String url, String paramsJson) {
		RestTemplate restT = RestTemplateUtil.getInstance("utf-8");
		return restT.postForObject(url, paramsJson, String.class);
	}
	
	
	public static String sendForPostBody(String url, Object paramsJson,String token) throws Exception {
		
		LinkedMultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
		headers.put("Content-Type", Collections.singletonList("application/json;charset=utf-8"));
		headers.put(HttpHeaders.AUTHORIZATION, Collections.singletonList(token));
		HttpEntity<String> formEntity = new HttpEntity<String>(JSONObject.fromObject(paramsJson).toString(), headers);
		RestTemplate restTemplate = new RestTemplate(RestTemplateUtil.generateHttpRequestFactory());
		RequestCallback requestCallback = restTemplate.httpEntityCallback(formEntity, JSONObject.class);
		ResponseExtractor<ResponseEntity<String>> responseExtractor = restTemplate.responseEntityExtractor(String.class);
		ResponseEntity<String> response=null;
		response = restTemplate.execute(url, HttpMethod.POST, requestCallback, responseExtractor);	
		
		return response.getBody();
		
	}
	
	public static String sendForDelete(String url) {
		HttpHeaders header = new HttpHeaders();
		HttpEntity<Object> httpEntity = new HttpEntity<Object>(null, header);
		RestTemplate restT = RestTemplateUtil.getInstance("utf-8");
		Map<String, Object> params = new HashMap<String,Object>();
		return restT.exchange(url, HttpMethod.DELETE, httpEntity, String.class, params).getBody();
	}
	
	/**
     * 向指定URL发送GET方法的请求
     * 
     * @param url
     *            发送请求的URL
     * @param param
     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static List<String> sendGet(String url, String auth) {
    	List<String> lineList = new ArrayList<String>();
        BufferedReader in = null;
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("Authorization", auth);
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
            	lineList.add(line);
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return lineList;
    }
    
	public static String okGet(String url, String auth) throws SQLException, IOException {
		OkHttpClient client = new OkHttpClient();

		Request request = new Request.Builder()
		  .url(url)
		  .get()
		  .addHeader("Authorization", auth)
		  .addHeader("Accept", "*/*")
		  .addHeader("Cache-Control", "no-cache")
		  .addHeader("Connection", "keep-alive")
		  .addHeader("cache-control", "no-cache")
		  .build();

		Response response = client.newCall(request).execute();
		return response.body().string();
	}
	
	public static void main(String[] args) throws SQLException, IOException {
		//System.out.println(okGet("http://172.30.132.167:19201/dp_dwd_access_detail_index/_search", ""));
		System.out.println(sendForDelete("http://localhost:18894/assetPanorama/project/develop"));
	}
}
